<!-- 使用 type="home" 属性设置首页，其他页面不需要设置，默认为page；推荐使用json5，更强大，且允许注释 -->
<route lang="json5">
{
  style: {
    navigationBarTitleText: '产品详情',
    enablePullDownRefresh: false,
  },
}
</route>
<template>
  <view class="page" v-if="course">
    <view>
      <!-- https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/2minute-demo.mp4 :trialTime="20" :seekTime="5" -->
      <sunny-video
        v-if="course.video"
        ref="sunnyVideoRef"
        :key="state.playId + new Date().getTime()"
        :title="state.videoTitle"
        videoHeight="400rpx"
        :poster="course.image"
        :src="`${course.video}?${state.playId}`"
        :seekTime="state.seekTime"
        @timeupdate="handleTimeupdate"
        @ended="handleVideoEnded"
        @playError="onPlayschedule"
        @pause="onPlayschedule"
      />
      <wd-swiper
        v-else
        height="400rpx"
        img-mode="aspectFill"
        :list="course.goods_image"
        autoplay
        :indicator="{ type: 'dots-bar' }"
        customItemClass="rounded-sm"
        customClass="mt-4"
      ></wd-swiper>
    </view>

    <view class="product-info">
      <view class="text-base text-md font-bold flex">
        <text class="flex-1 mr-6 leading-[48rpx]">{{ course.name }}</text>
        <view class="flex gap-x-5">
          <share-button />
          <collect-button
            v-model="course.is_collect"
            :params="{ goods_id: course.id, is_collect: Number(!course.is_collect) }"
            api="/shopapi/collect/handleCollectgoods"
          />
        </view>
      </view>

      <view class="mt-[20rpx] flex justify-between">
        <view>
          <text class="text-[30rpx]">￥</text>
          <text class="text-[60rpx]">{{ course.sell_price }}</text>
        </view>
        <view class="text-[#9A9A9A] text-xs flex items-center">
          <i class="w-[6rpx] h-[6rpx] rounded-1/2 bg-[#9A9A9A] mr-1"></i>
          <text>已售{{ course.sales_num }}</text>
        </view>
      </view>
      <discount-bar
        :level-name="course.levelName"
        custom-class="h-[62rpx] mt-[20rpx]"
        left-class="text-[32rpx]"
        right-class="text-sm"
        :price="course.member_price"
      />

      <view v-if="coupon" class="mt-2.5 flex items-center text-base" @click="openCouponPopup">
        <text class="mr-4 text-sm">优惠</text>
        <view class="coupon text-[26rpx] relative h-[58rpx] flex">
          <!-- <image class="absolute left-0 top-[-1rpx] h-[58rpx] " mode="heightFix" src="/static/coupon.png"></image> -->
          <text class="coupon-left pr-[10rpx] flex items-center justify-center h-full pl-2.5">
            {{ coupon.name }}
          </text>
          <text
            class="border border-solid border-[#ffe8bd] border-l-0 px-[10rpx] text-[#FFB329] flex items-center"
          >
            立减{{ coupon.money }}元
          </text>
        </view>
        <view class="ml-auto">
          <wd-icon color="var(--wot-color-theme)" name="arrow-right" size="24rpx"></wd-icon>
        </view>
      </view>
    </view>

    <view class="mt-1">
      <wd-tabs v-model="state.curTab" sticky animated>
        <wd-tab title="课程简介" :name="0">
          <view class="px-4">
            <uv-parse :nodes="imgDeal(course.content)"></uv-parse>
          </view>
        </wd-tab>
        <wd-tab title="课程目录" :name="1">
          <view class="px-4">
            <catalog
              :modelValue="state.curPlayIndex"
              :list="state.catalogList"
              @update:modelValue="handleToggleVideo"
              @unlock="handleUnlockClick"
            />
          </view>
        </wd-tab>
      </wd-tabs>
    </view>

    <pageFooter :status="course.type" @addCar="handleAddCar" @buy="handleBuy" />

    <wd-popup
      v-model="state.showCouponPopup"
      lock-scroll
      position="bottom"
      :safe-area-inset-bottom="true"
      custom-class="rounded-lg"
    >
      <view class="px-4">
        <view class="py-4 flex justify-between items-center text-base">
          <text>优惠券</text>
          <wd-icon name="close" size="22rpx" color="#141719" @click="closeCouponPopup"></wd-icon>
        </view>
        <view class="max-h-[800rpx] overflow-auto">
          <coupon-list :isGet="1" :list="couponList" @get="handleGetCoupon"></coupon-list>
        </view>
      </view>
    </wd-popup>
  </view>
</template>

<script setup>
import { nextTick } from 'vue'
import dayjs from 'dayjs'
import { fetchCouponList, fetchCourseDetail, fetchSchedule } from '@/service/course'
import { addCar } from '@/service/car'
import { fetchClock, fetchClockRules } from '@/service/user'
import { showToast } from '@/utils/uni'
import { to } from '@/utils/navigation'
import useUserStore from '@/store/user'
import { imgDeal } from '@/utils/format'
import useRequest from '@/hooks/useRequest'
import CouponList from '@/components/coupon-list/coupon-list.vue'
import pageFooter from './components/product-detail-float-bottom.vue'
import catalog from './components/course-catalogue.vue'

defineOptions({
  options: {
    styleIsolation: 'shared',
  },
})
const sunnyVideoRef = ref(null)
const userStore = useUserStore()
let today = getTodayDate()

let duration = userStore.viewDuration.duration

const state = ref({
  showCouponPopup: false,
  courseId: '',
  curTab: 0,
  curPlayIndex: -1,
  catalogList: [],
  currentTime: 0,
  playId: '',
  videoTitle: '',
  seekTime: 0,
  watchKnow: 0,
})

const { loading, run, data: course } = useRequest(fetchCourseDetail)
const { run: loadCouponList, data: couponData } = useRequest(fetchCouponList)
const couponList = computed(() => {
  return couponData && couponData.value ? couponData.value.lists : []
})
const coupon = computed(() => {
  return Array.isArray(couponList.value) && couponList.value.length > 0 && couponList.value[0]
})

function getTodayDate() {
  return dayjs().format('YYYY-MM-DD')
}

function handleGetCoupon(res) {
  showToast(res.msg, () => {
    loadCouponList()
  })
}

function openCouponPopup() {
  state.value.showCouponPopup = true
}

function closeCouponPopup() {
  state.value.showCouponPopup = false
}

function handleVideoEnded() {
  state.value.currentTime = 0
  onPlayschedule()
}

function handleSeeking() {
  console.log('正在拖拽进度条')
}

function onPlayschedule() {
  const { courseId, playId, currentTime, curPlayIndex } = state.value
  if (curPlayIndex < 0 || !userStore.isLogin) return
  fetchSchedule({
    id: playId || courseId,
    watch: currentTime,
  }).then(() => {
    state.value.catalogList[curPlayIndex].watch = currentTime
  })
}

function handleUnlockClick() {
  showToast('课程尚未解锁')
}

// 获取打卡状态
function getClockRules() {
  fetchClockRules().then((res) => {
    const { user, watchKnow } = res.data
    userStore.updateClockStatus(user.today_sign)
    state.value.watchKnow = watchKnow
  })
}

async function handleToggleVideo(i) {
  today = getTodayDate()
  const { video: curVideo, playId } = state.value
  if (curVideo && playId) await onPlayschedule()

  const { video, id, title, watch, video_cover } = state.value.catalogList[i]
  course.value.video = video
  state.value.curPlayIndex = i
  state.value.playId = id
  state.value.videoTitle = title
  state.value.seekTime = watch ? parseInt(watch) : 0

  course.value.image = video_cover
  nextTick(() => {
    setTimeout(() => {
      sunnyVideoRef.value?.seek(state.value.seekTime)
      sunnyVideoRef.value?.playVideo()
    }, 100)
  })
}

function getProductDetail() {
  const { courseId } = state.value
  run({
    id: courseId,
    visit: 1,
  }).then(() => {
    const { chapter } = course.value
    state.value.catalogList = chapter
    state.value.curPlayIndex = state.value.catalogList.findIndex((item) => item.id == courseId)
  })
}

function handleAddCar() {
  const { spec_value_list, total_stock } = course.value
  if (!total_stock) return showToast('库存不足')
  addCar({
    item_id: spec_value_list[0].id,
    goods_num: 1,
  }).then((res) => {
    showToast(res.msg)
  })
}

function handleBuy() {
  const { spec_value_list, total_stock } = course.value
  if (!total_stock) return showToast('库存不足')
  const skuId = spec_value_list[0].id
  to(`pages-sub/product/create-order?goods_id=${skuId}&source=buy_now`)
}

function handleTimeupdate(e) {
  const { currentTime } = e.detail
  let next = currentTime - state.value.currentTime
  if (next > 0 && next < 1) {
    duration += next
  }

  state.value.currentTime = currentTime
  if (userStore.viewDuration.time !== today) {
    userStore.setViewDuration({
      time: today,
      duration: duration,
    })
  } else {
    userStore.setViewDuration({
      duration: duration,
    })
    const { viewDuration, userInfo } = userStore

    if (viewDuration.duration >= state.value.watchKnow && !userInfo.clock_status) {
      fetchClock()
      userStore.updateClockStatus(true)
    }
  }
}

onLoad(async (options) => {
  state.value.courseId = options.id || ''
})
onShow(() => {
  getProductDetail()
  loadCouponList()
  userStore.isLogin && getClockRules()
})

onUnload(onPlayschedule)
onHide(onPlayschedule)
</script>

<style lang="scss" scoped>
.page {
  @include addSafeArea(146rpx);

  .product-info {
    padding: 28rpx 20rpx 20rpx;
    box-shadow: 0rpx 3rpx 10rpx 1rpx rgba(0, 0, 0, 0.1);
  }

  .coupon {
    padding-right: 10rpx;

    &-left {
      min-width: 160rpx;
      background: url(~@/static/coupon.png) no-repeat center/cover;
    }
  }
}

::v-deep .wd-sticky {
  border-bottom: 1px solid #ededed;
}
</style>
